package cn.loioi.web.controller.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import cn.loioi.web.common.BaseJSONController;

@RestController
@RequestMapping("/api/test")
public class TestApiContorller extends BaseJSONController {
	/**
	 * 代理请求测试
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@PostMapping("proxy.json")
	public void proxy(HttpServletResponse response, Model model) throws IOException {
		String result = "{\"msg\":\"获取数据失败\",\"success\":false}";
		try {
			URL url = new URL("http://www.jqueryflottutorial.com/AjaxUpdateChart.aspx?_=" + (new Date()).getTime());
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			result = String.valueOf(bufferedReader.readLine());
		} catch (Exception e) {
		}
		response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.getWriter().println(result);
	}

	/**
	 * OPTION 请求无响应内容测试
	 */
	@RequestMapping(value = "proxy.json", method = RequestMethod.OPTIONS)
	public void apiOptions() {
		logger.debug("OPTIONS HttpServletRequest");
	}

	@RequestMapping(value = "test.json")
	public List<String> apiOptions(Model model) {
		return Lists.newArrayList("1", "2");
	}
}
